#!/usr/bin/env python

import sys, os, shutil
from os3.dbm.dbmanager import DBManager

import datetime, re

from PIL import Image
from PIL.ExifTags import TAGS

IMAGES_SRC_PATH = "/Volumes/Dati/www/fotogallery/"

IMAGE_BASE_PATH = "/images/images/"
IMAGE_THUMB_PATH = "/images/thumbs/"


def _scale ( image, width, height ):
	start_w, start_h = image.size
	start_w = float ( start_w )
	start_h = float ( start_h )

	width = float ( width )
	height = float ( height )

	if ( start_w / start_h ) > ( width / height ):
		nx = width
		ny = ( width * start_h ) / start_w
	else:
		nx = ( height * start_w ) / start_h
		ny = height

	nx = int ( nx )
	ny = int ( ny )

	image = image.resize ( ( nx, ny ), Image.ANTIALIAS )

	return image


def _rotate ( path, direction ):
	if direction == 'left':
		angle = 90
	else:
		angle = 270

	im = Image.open ( path )
	im = im.rotate ( angle )
	im.save ( path, quality = 100 )


def _parse_exif ( img ):
	ret = {}

	try:
		i = Image.open ( img )

		ret [ "Width" ] = i.size [ 0 ]
		ret [ "Height" ] = i.size [ 1 ]

		info = i._getexif ()

		if not info: return ret

		for tag, value in info.items():
			decoded = TAGS.get ( tag, tag )
			ret [ decoded ] = value
	except:
		pass

	return ret


def _html_ent ( s ):
	rex = re.compile ( r"""([^a-zA-Z0-9,.:;=!?+\/_ |@-\\(\\)<>\n\r'"&-])""" )

	def _repl ( m ):
		s = m.group ( 0 )
		u = s.decode ( "latin1" )
		return "&#" + str ( ord ( u ) ) + ";"

	res = rex.sub ( _repl, s )

	return res


def _import ( name, descr, date, upfile ):

	dbm_dest.insert ( "accumulus_img", {
		"created": date,
		"creator": 1,
		"name": _html_ent ( name ),
		"descr": _html_ent ( descr )
	} )
	
	iid = dbm_dest.insert_id ()

	# save the image file
	p, ext = os.path.splitext ( upfile [ "filename" ] )
	ext = ext.lower ()

	t = datetime.date ( * [ int ( x ) for x in date.split ( "-" ) ] )
	pname = IMAGE_BASE_PATH + "%d/%02d_%02d" % ( t.year, t.month, t.day )
	fname = pname + "/%d.jpg" % iid

	try: os.makedirs ( pname )
	except: pass
	try: os.remove ( fname )
	except: pass

	ptname = IMAGE_THUMB_PATH + "%d/%02d_%02d" % ( t.year, t.month, t.day )
	th_name = ptname + "/%d.jpg" % iid

	try: os.makedirs ( ptname )
	except: pass
	try: os.remove ( th_name )
	except: pass

	shutil.copyfileobj ( upfile [ 'file' ], open ( fname, "wb" ) )

	# creo il thumbnail
	img = Image.open ( fname )

	thumb = _scale ( img, 200, 160 )
	thumb.save ( th_name, quality = 100 )

	# parso l'exif e aggiorno il db
	ex = _parse_exif ( fname )
	size = os.fstat ( upfile [ "file" ].fileno () ) [ 6 ]

	shot_date = ex.get ( "DateTimeOriginal" ) or "*NOW()"
	orient = int ( ex.get ( "Orientation", 0 ) )
	if orient < 5:
		orient = 'o'
	else:
		orient = 'v'

	dbm_dest.update ( "accumulus_img", {
		"fsize": size,
		"shot_date": shot_date,
		"orient": orient,
		"dx": ex.get ( "Width", 0 ),
		"dy": ex.get ( "Height", 0 )
	}, "id = %s" % iid )
	
	return iid


# MAIN
dbm_src = DBManager ( DBManager.DBM_TYPE_MYSQL )
dbm_src.connect ( host = '192.168.77.33', user = 'accumulus', passwd = 'AievveA', db = 'accumulus' )

dbm_dest = DBManager ( DBManager.DBM_TYPE_MYSQL )
dbm_dest.connect ( host = 'mysql', user = 'accumulus', passwd = 'accumulus', db = 'accumulus' )

#dbm_dest.execute ( "TRUNCATE accumulus_img" )

count = 0

rs = dbm_src.select ( "datasrc_12", "*" )
print "START"
for r in rs:
	count += 1

	lrs = dbm_dest.single_row ( "temp_log", "id", "id = %s" % r [ "id" ] )
	if lrs:
		if (count % 100) == 0: print "SKIP: %s" % count
		continue

	name = r.get ( "evento", "" )
	descr = r.get ( "descrizione", "" )

	name = name.replace ( "\\'", "'" )
	descr = descr.replace ( "\\'", "'" )

	fspath = r [ "fspath" ]
	fspath = fspath.rstrip ( "/" )
	fsp = fspath.split ( "/" )
	
	year = fsp [ -2 ]
	md = fsp [ -1 ].split ( "_" )
	if len ( md ) < 2:
		md = fsp [ -1 ].split ( "-" )
	if len ( md ) < 2:
		sys.stderr.write ( "BAD DIRECTORY: %s FILE_ID: %s\n" % ( fspath, r [ "id" ] ) )
		continue

	date = "%s-%s-%s" % ( year, md [ 0 ], md [ 1 ]  )

	fname = IMAGES_SRC_PATH + r.get ( "fspath", "" ) + str ( r [ "id" ] ) + ".jpg"

	if not os.path.isfile ( fname ):
		sys.stderr.write ( "FILE NOT FOUND: %s\n" % fname )
		continue

	if (count % 10) == 0: print count

	upfile = {
		"filename":	fname,
		"file":		open ( fname, "rb" )
		#"file":		open ( "test.jpg", "rb" )
	}

	try:
		_import ( name, descr, date, upfile )

		dbm_dest.insert ( "temp_log", { "id": r [ "id" ] } )

	except KeyboardInterrupt:
		pass

	except:
		sys.stderr.write ( "EXCEPTION IMPORTING IMAGE: %s %s\n" % ( r [ "id" ], fspath ) )


